package one.stand.controller;

import cn.hutool.core.util.StrUtil;
import com.jmp.api.user.dto.PersonalIsCollectionResponse;
import com.jmp.api.user.dto.WebsiteInfoResponse;
import com.jmp.api.user.dto.WxFormIdRequest;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.MessageApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AddressFeign;
import com.jmp.feign.MessageFeign;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.WebsiteFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.CollectionDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.UserDto;
import one.stand.mapper.CompanyRecruitMapper;
import one.stand.mapper.GoodsApiUserMapper;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.AddressResponse;
import one.stand.response.CompanyRecruitResponse;
import one.stand.service.*;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * 个人中心
 *
 * @author Administrator
 */
@RestController
@RequestMapping("userApi/personal")
@Api(description = "个人中心")
public class PersonalController extends BaseController {

    @Autowired
    private MessageFeign messageFeign;
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private WebsiteFeign websiteFeign;
    @Autowired
    private AddressFeign addressFeign;

    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private CompanyRecruitMapper companyRecruitMapper;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private CompanyShowroomService companyShowroomService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;

    @Autowired
    private GoodsApiUserMapper goodsApiUserMapper;

    @ApiOperation(value = "添加我的地址")
    @PostMapping("/addAddress")
    @SecurityAuthCheck
    public ResultModel addAddress(@RequestAttribute AddressRequest request) {

        ResultModel resultModel = addressFeign.save(AddressSaveDto.builder()
                .userId(request.getId().intValue())
                .locationAddress(request.getLocationAddress())
                .detailedAddress(request.getDetailedAddress())
                .isDefault(request.getIsdefault())
                .receiveName(request.getReceiveName())
                .receivePhone(request.getReceivePhone())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success("保存成功");
    }

    @ApiOperation(value = "修改我的地址")
    @PostMapping("/updAddress")
    @SecurityAuthCheck
    public ResultModel updAddress(@RequestAttribute AddressRequest request) {

        ResultModel resultModel = addressFeign.save(AddressSaveDto.builder()
                .addressId(request.getAddressId())
                .locationAddress(request.getLocationAddress())
                .detailedAddress(request.getDetailedAddress())
                .isDefault(request.getIsdefault())
                .receiveName(request.getReceiveName())
                .receivePhone(request.getReceivePhone())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success("修改成功");
    }

    @ApiOperation(value = "删除我的地址")
    @PostMapping("/delAddress")
    @SecurityAuthCheck
    public ResultModel delAddress(@RequestAttribute AddressRequest request) {
        String[] ids = request.getAddressIds().split(StrUtil.COMMA);
        for (String id : ids) {
            ResultModel resultModel = addressFeign.remove(AddressRemoveDto.builder()
                    .addressId(Integer.valueOf(id))
                    .build());
            AssertUtil.isTrue(resultModel);
        }
        return ResultModel.success();
    }

    @ApiOperation(value = "查询我的地址")
    @PostMapping("/getAddress")
    @SecurityAuthCheck
    public ResultModel getAddress() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        ResultModel<AddressListVo> resultModel = addressFeign.list(AddressListDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(resultModel);
        List<AddressListVo.Address> list = resultModel.getData().getAddressList();
        List<AddressResponse> responseList = ConvertUtils.list(list, address -> {
            AddressResponse addressResponse = new AddressResponse();
            addressResponse.setAddressId(address.getAddressId());
            addressResponse.setLocationAddress(address.getLocationAddress());
            addressResponse.setDetailedAddress(address.getDetailedAddress());
            addressResponse.setReceiveName(address.getReceiveName());
            addressResponse.setReceivePhone(address.getReceivePhone());
            addressResponse.setIsdefault(address.getIsDefault());
            return addressResponse;
        });
        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "我的地址设置为默认值")
    @PostMapping("/isdefult")
    @SecurityAuthCheck
    public ResultModel isdefult(@RequestAttribute AddressRequest request) {

        ResultModel resultModel = addressFeign.defaultSet(AddressDefaultSetDto.builder().addressId(request.getAddressId()).build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @PostMapping("/addCollection")
    @ApiOperation(value = "添加收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemType", value = "收藏对象类型（1产品，2文章，3企业）", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "itemId", value = "收藏对象ID", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck
    public ResultModel addCollection(@RequestAttribute CollectionRequest request) {
        return userFegin.addCollection(request);
    }

    @ApiOperation(value = "判断是否已经收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemType", value = "收藏对象类型（1产品，2文章，3企业）", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "itemId", value = "收藏对象ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/getIsCollection")
    @SecurityAuthCheck
    public ResultModel<PersonalIsCollectionResponse> getIsCollection(@RequestAttribute CollectionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CollectionDto obj = recordPublicService.getCollection(request.getId().intValue(), request.getItemType(), request.getItemId());
        if (Objects.isNull(obj)) return ResultModel.fail();

        PersonalIsCollectionResponse response = PersonalIsCollectionResponse.builder()
                .collectionId(obj.getCollectionId())
                .status(1)
                .build();
        return ResultModel.success(response);
    }

    @PostMapping("/delCollection")
    @ApiOperation(value = "取消收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemType", value = "收藏对象类型（1产品，2文章，3企业）", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "itemId", value = "收藏对象ID", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck
    public ResultModel delCollection(@RequestAttribute CollectionRequest request) {
        return userFegin.delCollection(request);
    }

    @ApiOperation(value = "查询收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemType", value = "收藏对象类型（1产品，2文章，3企业）", required = true, paramType = "Integer"),
    })
    @PostMapping("/getCollection")
    @SecurityAuthCheck
    public ResultModel getCollection(@RequestAttribute CollectionRequest request) {
        return userFegin.getCollection(request);
    }


    @PostMapping("/getCompanyAllInfo")
    @ApiOperation(value = "查询所有公司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyName", value = "公司名称", paramType = "String"),
    })
    public ResultModel getCompanyAllInfo(@RequestAttribute CompanyRequest request) {
        return userFegin.getCompanyAllInfo(request);
    }

    @PostMapping("/getWebsiteInfo")
    @ApiOperation(value = "查询公司官网")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "websiteId", value = "官网id", paramType = "Integer"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyName", value = "公司名称", paramType = "Integer"),
    })
    @SecurityAuthCheck
    public ResultModel<WebsiteInfoResponse> getWebsiteInfo(@RequestAttribute WebsiteRequest request) {
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.checkParamFail();
        }
        Website model = websiteService.getByCompanyId(request.getCompanyId());
        if (model == null) {
            return ResultModel.noData();
        }
        Company company = companyBaseService.getById(request.getCompanyId());
        List<CompanyRecruitModel> recruitModels = companyRecruitMapper.select(new CompanyRecruitModel() {{
            setCompanyId(request.getCompanyId());
        }});
        //视频
        ResultModel<WebsiteVideoVo> resultModel = websiteFeign.video(WebsiteVideoDto.builder().companyId(request.getCompanyId()).build());
        AssertUtil.isTrue(resultModel);
        List<WebsiteInfoResponse.Video> videoModels = ConvertUtils.list(resultModel.getData().getVideoList(), video -> {
            return WebsiteInfoResponse.Video.builder()
                    .videoId(video.getVideoId())
                    .url(video.getUrl())
                    .describes(video.getDescribes())
                    .cover(video.getCover())
                    .sort(video.getSort())
                    .build();
        });
        boolean fal = model.getWebsiteId() != null && (request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId()));
        if (fal) {
            //添加查看记录
            SeeRecordWebsiteRequest recordWebsiteRequest = SeeRecordWebsiteRequest.builder()
                    .userId(request.getId().intValue())
                    .cardId(request.getCardId())
                    .companyId(request.getCompanyId())
                    .itemId(model.getWebsiteId())
                    .build();
            seeRecordFeign.website(recordWebsiteRequest);
        }

        //主推商品
        List<Goods> mainPush = goodsApiUserMapper.selectMainPush(request.getCompanyId());
        List<WebsiteInfoResponse.Goods> mainGoodsList = ConvertUtils.list(mainPush, goods -> WebsiteInfoResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                .build());
        //每日精选
        List<Goods> daySelect = goodsApiUserMapper.selectDaySelect(request.getCompanyId());
        List<WebsiteInfoResponse.Goods> dayGoodsList = ConvertUtils.list(daySelect, goods -> WebsiteInfoResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(goodsPhotoService.getPath(goods.getGoodsId()))
                .build());
        if (OneListUtil.isEmpty(mainGoodsList) && OneListUtil.isNotEmpty(dayGoodsList)) {
            if (dayGoodsList.size() > 3) {
                mainGoodsList = dayGoodsList.subList(0, 3);
            } else {
                mainGoodsList = dayGoodsList;
            }
        }

        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(request.getCompanyId());

        WebsiteInfoResponse websiteResponse = WebsiteInfoResponse.builder()
                .photos(model.getPhotos())
                .companyIntroduce(model.getCompanyIntroduce())
                .goodsIntroduce(model.getGoodsIntroduce())
                .address(model.getAddress())
                .latitude(model.getLatitude())
                .longitude(model.getLongitude())
                .phone(model.getPhone())
                .showRoomState(CompanyBaseService.SHOWROOMSTATE_OPEN.equals(company.getShowroomstate()))
                .showRoomUrl(companyShowroom == null ? "" : companyShowroom.getVrUrl())//company 表展厅地址showRoomUrl 替换成 company_showroom 表vr_url
                .recruitModelList(recruitModels)
                .companyVideoModelList(videoModels)
                .mainGoodsList(mainGoodsList)
                .build();
        return ResultModel.success(websiteResponse);
    }

    @PostMapping("/getCompanyRecruit")
    @ApiOperation(value = "查询公司招聘信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
    })
    public ResultModel<List<CompanyRecruitResponse>> getCompanyRecruit(@RequestAttribute CompanyRecruitRequest request) {
        return userFegin.getCompanyRecruit(request);
    }

    @PostMapping("/addDemand")
    @ApiOperation(value = "用户提交需求信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "String"),
            @ApiImplicitParam(name = "phone", value = "电话", required = true, paramType = "String"),
            @ApiImplicitParam(name = "cardId", value = "入口名片id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "text", value = "需求内容", paramType = "String"),
    })
    @SecurityAuthCheck
    public ResultModel addDemand(@RequestAttribute DemandRequest request) {

        WebsiteDemandSaveDto saveDto = WebsiteDemandSaveDto.builder()
                .cardId(request.getCardId())
                .name(request.getName())
                .phone(request.getPhone())
                .text(request.getText())
                .optUserId(RequestContextHolder.getRequestContext().getUser().getUserId())
                .build();
        ResultModel resultModel = websiteFeign.demandSave(saveDto);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "用户保存formId")
    @PostMapping("/addFormId")
    @SecurityAuthCheck
    public ResultModel<Integer> addFormId(@RequestAttribute WxFormIdRequest request) {
        if (Objects.nonNull(request.getPositionIdx())
                && Objects.nonNull(request.getCarId())
                && !Objects.equals(request.getMyCardId(), request.getCarId())) {// push
            MessagePushType wxNoticeEnums = null;
            switch (request.getPositionIdx()) {
                case 0:
                    wxNoticeEnums = MessagePushType.CUSTOMER_ACCESS;
                    break;
                case 1:
                    wxNoticeEnums = MessagePushType.SEE_PRODUCT;
                    break;
                case 2:
                    wxNoticeEnums = MessagePushType.SEE_DYNAMIC;
                    break;
                case 3:
                    wxNoticeEnums = MessagePushType.SEE_OFFICIAL;
                    break;
                case -1:
                default:
                    logger.warn("PositionIdx({}) is not match", request.getPositionIdx());
            }
            if (Objects.nonNull(wxNoticeEnums)) {
                BusinessCard businessCardModel = businessCardBaseService.getCustomer(request.getCarId());
                UserDto user = userAdminService.get(request.getId());
                String[] fillData = {user.getName()};
                MessagePushRequest pushRequest = MessagePushRequest.builder()
                        .type(wxNoticeEnums)
                        .toId(businessCardModel.getUserId())
                        .fillData(fillData)
                        .build();
                messageFeign.push(pushRequest);
            }
        }

        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        MessageWxFormidRequest messageWxFormidRequest = MessageWxFormidRequest.builder()
                .userId(user.getUserId())
                .type(MessageApi.FORM_ID_TYPE_USER)
                .formId(request.getFormId())
                .companyKey(RequestContextHolder.getRequestContext().getRequest().getCompanyKey())
                .build();
        messageFeign.wxFormid(messageWxFormidRequest);

        return ResultModel.success(recordPublicService.formIdCount(messageWxFormidRequest.getUserId(), messageWxFormidRequest.getType()));
    }
}
